<template>
  <div>
    <cusDialog :title="menuForm.id ? '修改' : '添加'" ref="dialog" width="800px" headCss="float:left;"
      @confrim="confrimHandler" @hideHandler="hideHandler">
      <el-form :model="menuForm" ref="menuFormRef" :inline="true" :rules="rules" label-width="100px"
        class="demo-form-inline">
        <el-form-item label="节点类型" prop="resourceType">
          <el-radio-group v-model="menuForm.resourceType" class="ml-4">
            <el-radio :label="1">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="路由名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入路由名称"></el-input>
        </el-form-item>
        <el-form-item label="上级节点">
          <roleTree @getParentId="getParentId" ref="roleTreeRef"></roleTree>
        </el-form-item>
        <el-form-item label="节点路由" prop="url">
          <el-input v-model="menuForm.url" placeholder="请输入节点路由"></el-input>
        </el-form-item>
        <el-form-item label="文件路径" v-if="menuForm.resourceType == '2'">
          <el-select v-model="menuForm.filePath" filterable placeholder="请选择文件路径" style="width:100%">
            <el-option v-for="(item, index) in pageList" :key="item.index" :label="item.pagePath"
              :value="item.pagePath" />
          </el-select>
        </el-form-item>
        <el-form-item label="节点图标">
          <!-- 图标选择器 -->
          <icon-select v-model="menuForm.icon" />
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number v-model="menuForm.seq" :min="0" @change="inputChange" controls-position="right">
          </el-input-number>
        </el-form-item>
        <el-form-item label="按钮权限" v-if="menuForm.resourceType == '2'">
          <el-select v-model="menuForm.buttonList" multiple placeholder="请选择按钮权限" @change="changeSelect"
            style="width:100%">
            <el-option v-for="(item, index) in btnPermissions" :key="index" :label="item.buttonName"
              :value="item.buttonId" />
          </el-select>
        </el-form-item>
      </el-form>

      <el-alert title="菜单修改需刷新页面或重新登录后生效" type="info" show-icon :closable="false" />

    </cusDialog>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import {
  reqAddMenu,
  reqModifyMenu,
  reqSingalMenu,
  reqSaveBtn,
} from "@/api/business/menu";
import roleTree from "./roleTree.vue";
import iconList from "@/config/icons";
import { pageList } from "@/config/index";
import type { FormInstance, FormRules } from "element-plus";
const router = useRouter();
const formOrigin = () => ({
  name: "",
  pid: "",
  resourceType: "",
  apiUrl: "",
  url: "",
  filePath: "",
  icon: "",
  seq: 0,
  buttonList: [],
  tempList: [],
  list: [],
  id: "",
});

interface RuleForm {
  name: string;
  pid: string | number;
  resourceType: string | number;
  apiUrl: string;
  url: string;
  filePath: string;
  icon: string;
  seq: number;
  buttonList: number[];
  tempList: number[];
  list: object[];
  id: string | number;
}

const menuForm = ref(formOrigin());
const menuFormRef = ref();
const roleTreeRef = ref();
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "路由名称不能为空", trigger: "blur" }],
  url: [{ required: true, message: "路由节点不能为空", trigger: "blur" }],
  resourceType: [{ required: true, message: "节点类型不能为空", trigger: "blur" }],
});
const dialog = ref();
const emit = defineEmits(["handleGetMenuTree"]);

// 获取某组件的按钮列表
const btnPermissions = computed(() => {
  console.log(menuForm.value.filePath);
  let i = pageList.filter((val) => {
    return val.pagePath === menuForm.value.filePath;
  });
  if (i.length) {
    return i[0].btnPermissions;
  } else return [];
});
const changeSelect = (v) => {
  console.log("选中的值", v, menuForm.value.buttonList);
  console.log("监听的按钮ButtonList", buttonList.value);
  console.log("监听的按钮buttonListss", buttonLists.value);
  console.log("删除的按钮", deleteButtonList.value);
};
const buttonList = computed(() => {
  return btnPermissions.value.filter((v, ind) => {
    let flag = false;
    for (let i = 0; i < menuForm.value.buttonList.length; i++) {
      if (v.buttonId === menuForm.value.buttonList[i]) {
        flag = true;
      }
    }
    return flag;
  });
});
const buttonLists = computed(() => {
  let moreList: number[] = [];
  moreList = menuForm.value.buttonList.filter(
    (item) => !menuForm.value.tempList.includes(item)
  );
  let ss = btnPermissions.value.filter((item) =>
    moreList.includes(item.buttonId)
  );
  return ss;
});
const deleteButtonList = computed(() => {
  let deleteList: number[] = [];
  deleteList = menuForm.value.tempList.filter(
    (item) => !menuForm.value.buttonList.includes(item)
  );
  let intId = menuForm.value.list.filter((item) =>
    deleteList.includes(item.buttonId)
  );
  return intId.map((v) => v.id);
});
// 获取父节点id
const getParentId = (val) => {
  menuForm.value.pid = val;
};
const handleSaveBtn = () => {
  reqSaveBtn({
    pid: menuForm.value.id,
    buttonLists: JSON.stringify(buttonLists.value),
    deleteButtonList: JSON.stringify(deleteButtonList.value),
  }).then((res) => {
    if (res.code === 1) {
    }
  });
};
// 新增
const getAddMenu = () => {

  reqAddMenu({ ...menuForm.value }).then((res) => {
    console.log(res);
    if (res.code == 1) {
      handleSaveBtn();
      dialog.value.show = false;
      emit("handleGetMenuTree");
      ElMessage.success("添加成功");
    }
  });
};
// 编辑
const handleEditMenu = () => {
  console.log(menuForm.value, 777)
  reqModifyMenu({ ...menuForm.value }).then((res) => {
    console.log(res);
    if (res.code == 1) {
      handleSaveBtn();
      dialog.value.show = false;
      emit("handleGetMenuTree");
      ElMessage.success("编辑成功");
    }
  });
};

// 提交表单接口调取
const confrimHandler = () => {
  menuFormRef.value.validate((valid) => {
    if (valid) {
      if (menuForm.value.id) {
        // 调取编辑接口
        handleEditMenu();
      } else getAddMenu();
    } else {
      ElMessage.info("提交失败，请检查表单内容");
    }
  });
};

// 关闭对话框且重置数据
const hideHandler = () => {
  menuForm.value = formOrigin();
  roleTreeRef.value.clearSelected();
  menuFormRef.value.resetFields();
};

// 获取id详情数据
const getSingalMenu = () => {
  reqSingalMenu({ id: menuForm.value.id }).then((res) => {
    if (res.code == 1) {
      res.data.base.buttonList = [];
      res.data.base.tempList = [];
      res.data.base.list = res.data.list;
      // menuForm.value.filePath = res.data.base.filePath;
      menuForm.value.pid = res.data.base.pid;
      roleTreeRef.value.selectVal = menuForm.value.pid;
      btnPermissions.value.forEach((v, ind) => {
        res.data.list.forEach((item) => {
          if (v.buttonId === item.buttonId) {
            console.log("index", ind);
            res.data.base.buttonList.push(item.buttonId);
            res.data.base.tempList.push(item.buttonId);
          }
        });
      });
      menuForm.value = res.data.base;

    }
  });
};
// 显示对话框
const show = (id = "") => {
  dialog.value.show = true;
  if (id) {
    menuForm.value.id = id;
    getSingalMenu();
  }
  nextTick(() => {
    roleTreeRef.value.getAllMenuTree();
  });
};

defineExpose({ show });
</script>

<style lang="scss" scoped>
.treeBox {
  max-height: 400px;
  overflow-y: scroll;
}

.demo-form-inline {
  .el-form-item {
    width: 45%;
  }

  .el-input {
    --el-input-width: 100%;
  }

  // .el-select {
  //   --el-select-width: 220px;
  // }
}
</style>